package org.example.chat.service.impl;

import org.example.chat.api.Constant;
import org.example.chat.dao.FriendRelationRepository;
import org.example.chat.dao.FriendRequestRepository;
import org.example.chat.entity.FriendRequest;
import org.example.chat.service.IFriendRequestService;
import org.example.chat.vo.FriendRequestVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class FriendRequestServiceImpl extends BaseService implements IFriendRequestService {

    @Autowired
    private FriendRelationRepository friendRelationRepository;
    @Autowired
    private FriendRequestRepository friendRequestRepository;

    @Override
    public int addFriendRequest(FriendRequestVo friendRequestVo) {
        if (!friendRequestVo.getIsValidated()) {
            // 1. 判断是否已经是好友关系
            List<Object[]> relations = friendRelationRepository.findRelation(friendRequestVo.getRequestUserId(), friendRequestVo.getAcceptUserId());
            if (relations != null && relations.size() > 0) {
                // 已经是好友关系
                return 2;
            }
        }

        // 2. 判断是否已经发起过请求, 状态为【等待通过的记录】
        List<FriendRequest> requests = friendRequestRepository.findNoPassByRelation(friendRequestVo.getRequestUserId(), friendRequestVo.getAcceptUserId());
        if (requests != null && requests.size() > 0) {
            // 已经发起过添加好友请求
            return 1;
        }
        // 3. 发起添加请求
        FriendRequest friendRequest = new FriendRequest();
        friendRequest.setId(idGenerate.nextId("FriendRequest"));
        friendRequest.setRequestUserId(friendRequestVo.getRequestUserId());
        friendRequest.setAcceptUserId(friendRequestVo.getAcceptUserId());
        friendRequest.setStatus(Constant.FRIEND_REQUEST_STATUS_WAIT);
        friendRequest.setRequestDatetime(LocalDateTime.now());
        friendRequestRepository.save(friendRequest);
        return 0;
    }
}
